package com.sram.controller.user;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.sram.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import com.sram.entity.User;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserService userService;

	@RequestMapping(value="/login")
	public  @ResponseBody String regist( HttpServletRequest request,Model model, HttpServletResponse response,HttpSession session, User user) throws Exception {
//		System.out.println(user);
//		String mes =null;
//		List<User> dd =userService.getUserByName(user.getUserName(),user.getPassword());
//		if(dd.size() == 0){
//			mes = "密码错误";
//		}else{
//			session.setAttribute("userId",dd.get(0).getId());
//			session.setAttribute("userName",dd.get(0).getUserName());
//			mes = "ok";
//		}
//		return mes;
		List<User> dd =userService.getUserByName(user.getUserName(),user.getPassword());
		String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
		String username = user.getUserName();
		String password = user.getPassword();

		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		token.setRememberMe(true);
		System.out.println("为了验证登录用户而封装的token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
		//获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		try {
			//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
			System.out.println("对用户[" + username + "]进行登录验证..验证开始");
			currentUser.login(token);
			System.out.println("对用户[" + username + "]进行登录验证..验证通过");
			session.setAttribute("userId",dd.get(0).getId());
 			session.setAttribute("userName",dd.get(0).getUserName());
			resultPageURL = "ok";
		}catch(UnknownAccountException uae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
			request.setAttribute("message_login", "未知账户");
		}catch(IncorrectCredentialsException ice){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
			request.setAttribute("message_login", "密码不正确");
		}catch(LockedAccountException lae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
			request.setAttribute("message_login", "账户已锁定");
		}catch(ExcessiveAttemptsException eae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
			request.setAttribute("message_login", "用户名或密码错误次数过多");
		}catch(AuthenticationException ae){
			//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
			ae.printStackTrace();
			request.setAttribute("message_login", "用户名或密码不正确");
		}
		//验证是否登录成功
		if(currentUser.isAuthenticated()){
			System.out.println("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
		}else{
			token.clear();
		}
		return resultPageURL;
	}

	@RequestMapping(value="/out")
	public String out(HttpServletRequest request,HttpSession session){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
//		session.invalidate();
		return "redirect:/index.jsp";
	}
	@RequestMapping(value="/authCode")
	public void getAuthCode(HttpServletRequest request, HttpServletResponse response,HttpSession session)
			throws IOException {
		int width = 63;
		int height = 37;
		Random random = new Random();
		//设置response头信息
		//禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		//生成缓冲区image类
		BufferedImage image = new BufferedImage(width, height, 1);
		//产生image类的Graphics用于绘制操作
		Graphics g = image.getGraphics();
		//Graphics类的样式
		g.setColor(this.getRandColor(200, 250));
		g.setFont(new Font("Times New Roman",0,28));
		g.fillRect(0, 0, width, height);
		//绘制干扰线
		for(int i=0;i<40;i++){
			g.setColor(this.getRandColor(130, 200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}

		//绘制字符
		String strCode = "";
		for(int i=0;i<4;i++){
			String rand = String.valueOf(random.nextInt(10));
			strCode = strCode + rand;
			g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
			g.drawString(rand, 13*i+6, 28);
		}
		//将字符保存到session中用于前端的验证
		session.setAttribute("strCode", strCode);
		g.dispose();

		ImageIO.write(image, "JPEG", response.getOutputStream());
		response.getOutputStream().flush();

	}
	//创建颜色
	Color getRandColor(int fc,int bc){
		Random random = new Random();
		if(fc>255)
			fc = 255;
		if(bc>255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r,g,b);
	}
	/*----------------------------------------------------------*/
	@RequestMapping(value="/getAllUser")
	public String getAllUser(HttpServletRequest request,Model model) throws Exception {
		List<User> ss = userService.getAll();
		model.addAttribute("users",ss);
		return "allUser";
	}
	@RequestMapping(value="/toAddAndUpUser")
	public String toAddAndUpUser(HttpServletRequest request,Model model) throws Exception {
		String id = request.getParameter("id");
		if( id != null){
			User  user = (User) userService.selectByPrimaryKey(Integer.valueOf(id));
			model.addAttribute("user",user);
		}
		return "user/addAndUpUser";
	}
	@RequestMapping(value="/addAndUpUser")
	public String addAndUpUser(HttpServletRequest request,Model model,User user) throws Exception {
		if(user.getId() == null){
			userService.insert(user);
		}else{
			userService.updateByPrimaryKey(user);
		}

		return "redirect:getAllUser.do";
	}
	@RequestMapping(value="/delUser")
	public @ResponseBody String delUser(HttpServletRequest request,Model model) throws Exception {
		String id = request.getParameter("id");
		userService.deleteByPrimaryKey(Integer.valueOf(id));
		return "success";
	}
	/*----------------------------------------------------------*/
	@RequestMapping(value="/main")
	public String main(){
		return "main";
	}
	@RequestMapping(value="/chuanzhi")
	public String chuanzhi(){
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser1")
	public String getUser1( Model model,User user){
		model.addAttribute("name",user.getUserName());
		model.addAttribute("pwd","dddddddddddd");
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser2")
	public String getUser2(HttpServletRequest request, Model model,User user){
		String username = request.getParameter("userName");
		String password = request.getParameter("password");
		model.addAttribute("name",username);
		model.addAttribute("pwd",password);
		return "chuanzhi";
	}
	@RequestMapping(value="/getUser3")
	public void getUser3(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		System.out.printf("getUser3-----------"+username);
		model.addAttribute("name",username);
		response.getWriter().write("阿斯蒂芬");
		response.getWriter().flush();
	}
	@RequestMapping(value="/getUser4")
	public void getUser4(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		model.addAttribute("name",username);
		List ss = new ArrayList();
		ss.add(new User("ss","dd"));
		ss.add(new User("ss2","dd2"));
		System.out.printf("getUser4-----------"+ss.toString());
		response.getWriter().write(JSON.toJSONString(ss));
		response.getWriter().flush();
	}
	@RequestMapping(value="/getUser5")
	public  @ResponseBody String  getUser5(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
//		return "ss";//中文乱码  ,produces = "application/json; charset=utf-8"  加上请求会反应慢
		return "杜浩";
	}
	@RequestMapping(value="/getUser6")
	public  @ResponseBody List<User> getUser6(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		String username = request.getParameter("userName");
		model.addAttribute("name",username);
		List ss = new ArrayList();
		ss.add(new User("胜多负少","dd"));
		ss.add(new User("水电费","dd2"));
		return ss;
	}
	@RequestMapping(value="/redirect")
	public  String redirect(RedirectAttributes attr) throws IOException {
		// 重定向中文乱码问题server.xml 设置URIEncoding="UTF-8"
		attr.addAttribute("ss","杜浩");
		return "redirect:redirect2.do";
	}
	@RequestMapping(value="/redirect2")
	public  String userList2(HttpServletRequest request, Model model,HttpServletResponse response,User user) throws IOException {
		System.out.println("redirect2................"+ request.getParameter("ss"));
		return "redirect";
	}
}
